package club.dataresources.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.util.Hashtable;

/**
 * @author tao
 */
public class QrCodeUtil {
    private static final int WIDTH = 430;
    private static final int HEIGHT = 430;
    private static final String FORMAT = "gif";

    /**
     * 生成二维码
     *
     * @param deviceNum
     * @param content
     * @return
     */
    public static File createQrCode(String targetPath, String deviceNum, String content) {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        // 指定纠错等级,纠错级别（L 7%、M 15%、Q 25%、H 30%）
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 内容所使用字符集编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置二维码边的空度，非负数
        hints.put(EncodeHintType.MARGIN, 1);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            // 生成二维码
            File folder = new File(targetPath);
            String path = folder.getAbsolutePath();
            //写出二维码
            File image = new File(path, deviceNum + "." + FORMAT);
            MatrixToImageWriter.writeToFile(bitMatrix, FORMAT, image);
            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
